package com.chenglu.android.index;

import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chenglu.android.R;
import com.chenglu.android.common.base.BaseMvpFragment;
import com.chenglu.android.common.base.Global;
import com.chenglu.android.common.net.Constant;
import com.chenglu.android.common.utils.LogUtils;
import com.chenglu.android.common.utils.SPUtils;
import com.chenglu.android.common.utils.Utils;
import com.chenglu.android.common.widget.UIndicator;
import com.chenglu.android.couponcenter.CouponCenterActivity;
import com.chenglu.android.goodsinfo.infoutils.GoodsInfoUtils;
import com.chenglu.android.index.adapter.HomePicAdapter;
import com.chenglu.android.index.adapter.HomeSellAdapter;
import com.chenglu.android.index.adapter.HomeTabTitleAdapter;
import com.chenglu.android.index.adapter.HomeTabTitleDataAdapter;
import com.chenglu.android.index.adapter.HomeTopicAdapter;
import com.chenglu.android.index.adapter.HomeTopicPagerAdapter;
import com.chenglu.android.index.adapter.NearbyShopAdapter;
import com.chenglu.android.index.adapter.TopicAdapter;
import com.chenglu.android.index.bean.BannerBeanList;
import com.chenglu.android.index.bean.IndexRecomBean;
import com.chenglu.android.index.bean.NearbyShopBean;
import com.chenglu.android.index.bean.PageListBean;
import com.chenglu.android.index.bean.TabTitleBean;
import com.chenglu.android.index.mvp.contract.IndexContract;
import com.chenglu.android.index.mvp.presenter.IndexPresenter;
import com.chenglu.android.index.nicegoods.NiceGoodsActivity;
import com.chenglu.android.index.selectcity.citypicker.CityPickerActivity;
import com.chenglu.android.index.selectcity.citypicker.utils.StringUtils;
import com.chenglu.android.mine.login.LoginActivity;
import com.chenglu.android.onelogin.OneKeyLoginActivity;
import com.chenglu.android.restaurant.RestaurantActivity;
import com.chenglu.android.search.SearchHistoryActivity;
import com.chenglu.android.supermarket.SuperMarkerActivity;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;

import net.lucode.hackware.magicindicator.MagicIndicator;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import me.relex.circleindicator.CircleIndicator;

/**
 * @author: lyj
 * @Created: by Copyright 2023 6 Guangzhou Hongma Technology Co., Ltd. All rights reserved.
 * @Description： 首页布局
 */
public class IndexFragment extends BaseMvpFragment<IndexPresenter> implements IndexContract.View, TopicAdapter.OnItemClickListener , HomeTopicAdapter.OnItemSellClickListener {



    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.ll_home_search)
    LinearLayout llHomeSearch;
    @BindView(R.id.nestedscrollView)
    NestedScrollView nestedscrollView;
    @BindView(R.id.bannerlist)
    Banner bannerlist;
    @BindView(R.id.rv_home_category)
    RecyclerView rvHomeCategory;
    @BindView(R.id.tv_day_sell)
    TextView tvDaySell;
    @BindView(R.id.tv_limit_killding)
    TextView tvLimitKillding;
    @BindView(R.id.seller_viewPager)
    ViewPager sellerViewPager;
    @BindView(R.id.seller_indicator)
    MagicIndicator sellerIndicator;
    @BindView(R.id.recommend_viewPager)
    ViewPager recommendViewPager;
    @BindView(R.id.recommend_indicator)
    MagicIndicator recommendIndicator;
    @BindView(R.id.rv_nearby_shop)
    RecyclerView rvNearbyShop;
    @BindView(R.id.tv_city_name)
    TextView tvCityName;
    @BindView(R.id.rv_tab_title)
    RecyclerView rvTabTitle;
    @BindView(R.id.rv_super_like)
    RecyclerView rvTabTitleData;
    @BindView(R.id.smartrefreshlayout)
    SmartRefreshLayout smartrefreshlayout;
    @BindView(R.id.indicator)
    CircleIndicator indicator;
    @BindView(R.id.ui_indicator)
    UIndicator uiIndicator;
    @BindView(R.id.ui_indicator2)
    UIndicator uiIndicator2;

    //分类的adapter
    private HomePicAdapter homePicAdapter;
    //附近好店的adapter
    private NearbyShopAdapter nearbyShopAdapter;

    private String lng, lat;

    private int current = 1;

    private String tab0 = "999";

    //分页的adapter
    private TopicAdapter menuAdapter;

    @Override
    protected int getLayoutId() {

        return R.layout.fragment_index_use;
    }

    public static IndexFragment newInstance() {
        IndexFragment indexFragment = new IndexFragment();
        return indexFragment;
    }


    @Override
    protected void initView() {

        mPresenter = new IndexPresenter();
        mPresenter.attachView(this);

//        /*滑动渐变的效果*/
//        appbarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
//            @Override
//            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
//                if (Math.abs(verticalOffset) < appBarLayout.getTotalScrollRange()) {
//                    //展开时
//                    //去掉默认的标题
//                    toolbar.setVisibility(View.VISIBLE);
//                    //隐藏toolbar
//                    viewToolbar.setVisibility(View.GONE);
//                    ivTest.setVisibility(View.GONE);
//                } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
//                    //折叠时
//                    //将标题设置为显示
//                    //显示toolbar
//                    viewToolbar.setVisibility(View.VISIBLE);
//                    ivTest.setVisibility(View.VISIBLE);
//                    toolbar.setVisibility(View.GONE);
//                }
//            }
//        });
        initCategoryRv();
        initNearbyShopRv();

        //banner
        mPresenter.getBannerList(Constant.shopsTypeId999, Constant.one);
        // 图片分类
        mPresenter.getPageList(Constant.one, Constant.one);


        //商超 精选等
        initTabTitleAdapter();

        initTitleDataAdapter();

        initRefreshLayout();
        //内容不跟随滑动
        smartrefreshlayout.setEnableFooterTranslationContent(false);

        //通过就给位置权限
        if (XXPermissions.isGranted(mContext, Permission.ACCESS_FINE_LOCATION, Permission.ACCESS_COARSE_LOCATION)) {
            getCurrentLocationLatLng();
        }else {
            lng = "113.244096";
            lat = "23.189989";
            // 附近好店
            mPresenter.getNearbyShop(lng, lat);
            //推荐
            mPresenter.getIndexRecom(setIndexRecomMap());
            //热销
            mPresenter.getIndexSell(setIndexMap());

            mPresenter.getTabTitle();
        }
    }


    List<IndexRecomBean.Data.Records> homeTitledataList = new ArrayList<>();
    private HomeTabTitleDataAdapter homeTabTitleDataAdapter;

    //推荐的商品列表 刷新和加载
    private void initTitleDataAdapter() {

        homeTabTitleDataAdapter = new HomeTabTitleDataAdapter(mContext, homeTitledataList);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 2);
        rvTabTitleData.setLayoutManager(gridLayoutManager);
        rvTabTitleData.setAdapter(homeTabTitleDataAdapter);

        homeTabTitleDataAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if(homeTabTitleDataAdapter.getData().get(position).getShopsTypeId()==2){
                    GoodsInfoUtils.goodsRestantInfo(mContext,homeTabTitleDataAdapter.getData().get(position).getId(),homeTabTitleDataAdapter.getData().get(position).getShopsTypeId());
                }else {
                    GoodsInfoUtils.goodsInfo(mContext,homeTabTitleDataAdapter.getData().get(position).getId()
                    ,homeTabTitleDataAdapter.getData().get(position).getShopsTypeId());
                }

            }
        });

    }

    //刷新
    private void initRefreshLayout() {
        smartrefreshlayout.setEnableLoadMore(false);
        smartrefreshlayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //id 需要传参过来
                current = 1;
                //需要清空数据再加
                homeTitledataList.clear();
                mPresenter.getTabTitleData(setTabTitleMap(true, tab0));


            }
        });
        smartrefreshlayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                current += 1;
                mPresenter.getTabTitleData(setTabTitleMap(true, tab0));


            }
        });
    }

    private HomeTabTitleAdapter tabTitleAdapter;
    List<TabTitleBean.Data> tabTitleList = new ArrayList<>();

    //标题数据的列表
    private void initTabTitleAdapter() {
        tabTitleAdapter = new HomeTabTitleAdapter(mContext, tabTitleList);
        rvTabTitle.setLayoutManager(new LinearLayoutManager(mContext,
                LinearLayoutManager.HORIZONTAL, false));

        rvTabTitle.setAdapter(tabTitleAdapter);
    }

    private Map<String, String> setIndexMap() {
        Map<String, String> map = new HashMap<>();
        map.put("lng", lng);
        map.put("lat", lat);
        map.put("isHotPlatform", "1");
//        map.put("current","1");
//        map.put("size","10");
        return map;
    }


    private Map<String, String> setIndexRecomMap() {
        Map<String, String> map = new HashMap<>();
        map.put("lng", lng);
        map.put("lat", lat);
        map.put("isRecommendPlatform", "1");
//        map.put("current","1");
//        map.put("size","10");
        return map;
    }

    private Map<String, String> setTabTitleMap(boolean istype, String shopsId) {
        Map<String, String> map = new HashMap<>();
        if (istype) {
            map.put("shopsTypeId", shopsId);
        }
        // 经纬度不授权 默认传0
        map.put("lng", lng);
        map.put("lat", lat);
        map.put("current", current + "");
        map.put("size", 20 + "");
        return map;
    }

    //附近好店rv
    List<NearbyShopBean.Data.Records> nearbyshopList = new ArrayList<>();

    private void initNearbyShopRv() {

        nearbyShopAdapter = new NearbyShopAdapter(mContext, nearbyshopList);
        //
        rvNearbyShop.setLayoutManager(new LinearLayoutManager(mContext,
                LinearLayoutManager.HORIZONTAL, false));

        rvNearbyShop.setAdapter(nearbyShopAdapter);

        nearbyShopAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //跳转店铺
                int shopsTypeId = nearbyShopAdapter.getData().get(position).getShopsTypeId();

                if(shopsTypeId==Constant.typeIdRestaurant || shopsTypeId==Constant.typeIdMinimart || shopsTypeId == Constant.typeIdPharmaceuticals ||shopsTypeId==Constant.typeIdBreed){
                    //跳转餐饮外卖首页
                }else {
                    //跳转商超的店铺首页
                    GoodsInfoUtils.goodsStoreInfo(mContext,nearbyShopAdapter.getData().get(position).getTenantId(),shopsTypeId);
                }
            }
        });
    }

    //图片分类的集合
    List<PageListBean.Data.Records> categoryList = new ArrayList<>();

    private void initCategoryRv() {

        homePicAdapter = new HomePicAdapter(mContext, categoryList);
        //
        rvHomeCategory.setLayoutManager(new GridLayoutManager(mContext, 5,
                LinearLayoutManager.VERTICAL, false));

        rvHomeCategory.setAdapter(homePicAdapter);

        homePicAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String categoryName = homePicAdapter.getData().get(position).getCategoryName();
                String id = homePicAdapter.getData().get(position).getId();
                if (categoryName.equals("商超")) {
                    mContext. startActivity(new Intent(getActivity(), SuperMarkerActivity.class)
                            .putExtra(SuperMarkerActivity.pid, id));
                } else if (categoryName.equals("餐饮")) {
                    mContext. startActivity(new Intent(getActivity(), RestaurantActivity.class)
                            .putExtra(SuperMarkerActivity.pid, id));
                }else if(categoryName.equals("领券中心")){
                    if(isLogin){
                        LogUtils.e("点击领劵中心");
                        mContext.startActivity(new Intent(getActivity(), CouponCenterActivity.class));
                    }else {
                       login();
                    }

                }

            }
        });
    }
    //跳转登录的方法
//    private void login() {
//
//        if (Utils.checkSim(mContext)) {
//            //判断是否是模拟器
//            if (Utils.isEmulator()) {
//                startActivity(new Intent(getActivity(), LoginActivity.class));
//            } else {
//                startActivity(new Intent(getActivity(), OneKeyLoginActivity.class));
//            }
//
//        } else {
//            startActivity(new Intent(getActivity(), LoginActivity.class));
//        }
//    }


    //分类图片集合
    List<IndexRecomBean.Data.Records> indexRecomList = new ArrayList<>();

    //推荐
    private void initTypeViewPager(int rowNum, int columnNum) {

        //1.根据数据的多少来分页，每页的数据为rw
        int singlePageDatasNum = rowNum * columnNum; //每个单页包含的数据量：2*4=8；
        int pageNum = indexRecomList.size() / singlePageDatasNum;//算出有几页菜单：20%8 = 3;
        if (indexRecomList.size() % singlePageDatasNum > 0) pageNum++;//如果取模大于0，就还要多一页出来，放剩下的不满项
        ArrayList<RecyclerView> mList = new ArrayList<>();
        for (int i = 0; i < pageNum; i++) {
            RecyclerView recyclerView = new RecyclerView(mContext);
            GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, columnNum) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            };
            recyclerView.setLayoutManager(gridLayoutManager);
            int fromIndex = i * singlePageDatasNum;
            int toIndex = (i + 1) * singlePageDatasNum;
            if (toIndex > indexRecomList.size()) toIndex = indexRecomList.size();
            //a.截取每个页面包含数据
            ArrayList<IndexRecomBean.Data.Records> menuItems = new ArrayList<>(indexRecomList.subList(fromIndex, toIndex));
            //b.设置每个页面的适配器数据
            menuAdapter = new TopicAdapter(mContext, menuItems);
            menuAdapter.setOnItemClickListener(this);
            //c.绑定适配器，并添加到list
            recyclerView.setAdapter(menuAdapter);
            mList.add(recyclerView);
        }
        //2.ViewPager的适配器
        HomeTopicPagerAdapter menuViewPagerAdapter = new HomeTopicPagerAdapter(mList);
        recommendViewPager.setAdapter(menuViewPagerAdapter);
        //3.动态设置ViewPager的高度，并加载所有页面
        int height = Global.dp2px(140);//这里的80为MainMenuAdapter中布局文件高度
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                indexRecomList.size() <= columnNum ? height : height * rowNum);
        recommendViewPager.setLayoutParams(layoutParams);
        recommendViewPager.setOffscreenPageLimit(pageNum - 1);
        final int finalPageNum = pageNum;

        uiIndicator.attachToViewPager(recommendViewPager);

//        indicator.setViewPager(recommendViewPager);

// optional
//        HomeTopicPagerAdapter.registerDataSetObserver(indicator.getDataSetObserver());

        //4.创建指示器
//        CircleNavigator commonNavigator = new CircleNavigator(mContext);
//
////        final CircleNavigator circleNavigator = new CircleNavigator(mContext);
//
////        commonNavigator.setAdjustMode(true);
//
//        commonNavigator.setCircleCount(finalPageNum);
//        commonNavigator.setCircleColor(Color.RED);
//
//
//        commonNavigator.setCircleSpacing(30);
//
////        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
////            @Override
////            public int getCount() {
////                return finalPageNum;
////            }
////
////            @Override
////            public IPagerTitleView getTitleView(Context context, int index) {
////
////                return new DummyPagerTitleView(context);
////            }
////
////            @Override
////            public IPagerIndicator getIndicator(Context context) {
////
////
////                return null;
////            }
////        });
//        //5.配置指示器，并和ViewPager产生绑定
//        recommendIndicator.setNavigator(commonNavigator);
//        ViewPagerHelper.bind(recommendIndicator, recommendViewPager);
    }


    List<IndexRecomBean.Data.Records> indexSellist = new ArrayList<>();

    private void initTypeViewPager2(int rowNum, int columnNum) {

        //1.根据数据的多少来分页，每页的数据为rw
        int singlePageDatasNum = rowNum * columnNum; //每个单页包含的数据量：2*4=8；
        int pageNum = indexSellist.size() / singlePageDatasNum;//算出有几页菜单：20%8 = 3;
        if (indexSellist.size() % singlePageDatasNum > 0) pageNum++;//如果取模大于0，就还要多一页出来，放剩下的不满项
        ArrayList<RecyclerView> mList = new ArrayList<>();
        for (int i = 0; i < pageNum; i++) {
            RecyclerView recyclerView = new RecyclerView(mContext);
            GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, columnNum) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            };

            recyclerView.setLayoutManager(gridLayoutManager);
            int fromIndex = i * singlePageDatasNum;
            int toIndex = (i + 1) * singlePageDatasNum;
            if (toIndex > indexSellist.size()) toIndex = indexSellist.size();
            //a.截取每个页面包含数据
            ArrayList<IndexRecomBean.Data.Records> menuItems = new ArrayList<>(indexSellist.subList(fromIndex, toIndex));
            //b.设置每个页面的适配器数据
            HomeTopicAdapter homeTopicAdapter = new HomeTopicAdapter(mContext, menuItems);
            homeTopicAdapter.setOnItemClickListener(this);
            //c.绑定适配器，并添加到list
            recyclerView.setAdapter(homeTopicAdapter);
            mList.add(recyclerView);
        }
        //2.ViewPager的适配器
        HomeTopicPagerAdapter menuViewPagerAdapter = new HomeTopicPagerAdapter(mList);
        sellerViewPager.setAdapter(menuViewPagerAdapter);
        //3.动态设置ViewPager的高度，并加载所有页面
        int height = Global.dp2px(140);//这里的80为MainMenuAdapter中布局文件高度
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                indexSellist.size() <= columnNum ? height : height * rowNum);
        sellerViewPager.setLayoutParams(layoutParams);
        sellerViewPager.setOffscreenPageLimit(pageNum - 1);

        uiIndicator2.attachToViewPager(sellerViewPager);

    }


    @Override
    public void onTopicItemClick(IndexRecomBean.Data.Records position, int shopsTypeId, String id) {
           GoodsInfoUtils.goodsInfo(mContext,id,shopsTypeId);
    }


    @Override
    public void onSellTopicItemClick(IndexRecomBean.Data.Records position, int shopsTypeId, String id) {
        GoodsInfoUtils.goodsInfo(mContext,id,shopsTypeId);
    }

    @Override
    public void onResume() {
        super.onResume();
        ImmersionBar.with(this)
                .fullScreen(true)
                .statusBarColorTransformEnable(false)
                .keyboardEnable(false)
                .navigationBarColor(R.color.white)
                .init();
    }

    private static final int REQUEST_CODE_PICK_CITY = 0;

    @OnClick({R.id.ll_home_search,R.id.tv_city_name,R.id.ll_find_goods,R.id.rl_daily_specials,R.id.rl_coupon_center})
    public void onViewClicked(View view) {

        switch (view.getId()){
            case R.id.tv_city_name:
                startActivityForResult(new Intent(getActivity(), CityPickerActivity.class),
                        REQUEST_CODE_PICK_CITY);
                break;

            case R.id.ll_home_search:
                startActivity(new Intent(getActivity(), SearchHistoryActivity.class)
                .putExtra(SearchHistoryActivity.SHOPSTYPEID,Constant.shopsTypeId999));
                break;
            case R.id.ll_find_goods:
                startActivity(new Intent(getActivity(), NiceGoodsActivity.class));
                break;
            case R.id.rl_daily_specials:
                startActivity(new Intent(getActivity(), NiceGoodsActivity.class));
                break;
            case R.id.rl_coupon_center:
                if(isLogin){
                    startActivity(new Intent(getActivity(), CouponCenterActivity.class));
                }else {
                    login();
                }

                break;
        }

    }

    //返回选中城市
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PICK_CITY && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                String city = data.getStringExtra(CityPickerActivity.KEY_PICKED_CITY);
//                if (!city.equals("全国")) {
//                    city += "市";
//                }
                tvCityName.setText(city);
            }
        }
    }


    @Override
    public void getBannerList(BannerBeanList bean) {

        List<String> imgs = new ArrayList<>();


        for (int i = 0; i < bean.getData().size(); i++) {
            imgs.add(bean.getData().get(i).getImg());
        }
        BannerUtils.initBanner(imgs, bannerlist);

    }


    @Override
    public void getPageList(PageListBean bean) {

        for (int i = 0; i < bean.getData().getRecords().size(); i++) {
            categoryList.add(bean.getData().getRecords().get(i));
        }
        homePicAdapter.notifyDataSetChanged();

    }


    @Override
    public void onNetOutTimeError(String tag) {
        super.onNetOutTimeError(tag);
        stopRefresh(smartrefreshlayout);
    }

    @Override
    public void getNearbyShop(NearbyShopBean bean) {

        for (int i = 0; i < bean.getData().getRecords().size(); i++) {
            nearbyshopList.add(bean.getData().getRecords().get(i));
        }
        nearbyShopAdapter.notifyDataSetChanged();
    }


    @Override
    public void getIndexRecom(IndexRecomBean bean) {

        for (int i = 0; i < bean.getData().getRecords().size(); i++) {
            indexRecomList.add(bean.getData().getRecords().get(i));
        }
        initTypeViewPager(1, 2);
    }


    @Override
    public void getIndexSell(IndexRecomBean bean) {

        for (int i = 0; i < bean.getData().getRecords().size(); i++) {
            indexSellist.add(bean.getData().getRecords().get(i));
        }
        initTypeViewPager2(1, 2);
    }


    @Override
    public void getTabTitle(TabTitleBean bean) {
        if (bean.getCode().equals(Constant.HTTPCODE200)) {

            for (int i = 0; i < bean.getData().size(); i++) {
                tabTitleList.add(bean.getData().get(i));
            }
            tabTitleAdapter.notifyDataSetChanged();

            //先把标题获取后再请求精选数据
            mPresenter.getTabTitleData(setTabTitleMap(true, tab0));
        }

        //点击事件
        tabTitleAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                tabTitleAdapter.setThisPosition(position);
                if (!homeTitledataList.isEmpty()) {
                    current = 1;
                    homeTitledataList.clear();
                }
                tab0 = tabTitleAdapter.getData().get(position).getShopsTypeId();
                mPresenter.getTabTitleData(setTabTitleMap(true, tabTitleAdapter.getData().get(position).getShopsTypeId()));
            }
        });
    }


    @Override
    public void getTabTitleData(IndexRecomBean bean) {

        stopRefresh(smartrefreshlayout);
        LogUtils.d("CCCCC = " + current * 10);
        if (bean.getData().getRecords().size() > 0) {
            for (int i = 0; i < bean.getData().getRecords().size(); i++) {
                homeTitledataList.add(bean.getData().getRecords().get(i));

            }
//            if (bean.getData().getTotal() < Constant.SIZETEN) {
//                smartrefreshlayout.setEnableRefresh(false);
//            }
////            View inflate = Global.inflate(R.layout.loadmore_addfooter_layout);
//            if (current * Constant.SIZETEN >= bean.getData().getTotal()) {
//////                inflate.setVisibility(View.VISIBLE);
//                smartrefreshlayout.setEnableLoadMore(false);
//////
//////                inflate.findViewById(R.id.tv_no_more).setBackgroundColor(getResources().getColor(R.color.color_f6f6f6));
//////                homeTabTitleDataAdapter.addFooterView(inflate);
//            } else {
//                smartrefreshlayout.setEnableLoadMore(true);
////                if(homeTabTitleDataAdapter.isFooterViewAsFlow()){
//////                   inflate.setVisibility(View.GONE);
////                }
//            }
            homeTabTitleDataAdapter.notifyDataSetChanged();
        }


    }




    //声明AMapLocationClient类对象
    AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    /**
     * 初始化定位并设置定位回调监听
     */
    private void getCurrentLocationLatLng() {
        //初始化定位
        try {
            mLocationClient = new AMapLocationClient(getActivity());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();

 /* //设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景） 设置了场景就不用配置定位模式等
    option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
    if(null != locationClient){
        locationClient.setLocationOption(option);
        //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
        locationClient.stopLocation();
        locationClient.startLocation();
    }*/
        // 同时使用网络定位和GPS定位,优先返回最高精度的定位结果,以及对应的地址描述信息
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //只会使用网络定位
        /* mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);*/
        //只使用GPS进行定位
        /*mLocationOption.setLocationMode(AMapLocationMode.Device_Sensors);*/
        // 设置为单次定位 默认为false
        mLocationOption.setOnceLocation(true);
        //设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。默认连续定位 切最低时间间隔为1000ms
        mLocationOption.setInterval(3500);
        //设置是否返回地址信息（默认返回地址信息）
        /*mLocationOption.setNeedAddress(true);*/
        //关闭缓存机制 默认开启 ，在高精度模式和低功耗模式下进行的网络定位结果均会生成本地缓存,不区分单次定位还是连续定位。GPS定位结果不会被缓存。
        /*mLocationOption.setLocationCacheEnable(false);*/
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    /**
     * 定位回调监听器
     */

    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            //检查位置权限
//            if (!IsGpsWork.isGpsEnabled(getApplicationContext())) {
//
//                ToastUtils.show("请打开GPS");
//            } else {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息
                    amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    double currentLat = amapLocation.getLatitude();//获取纬度
                    double currentLon = amapLocation.getLongitude();//获取经度


                    String province = amapLocation.getProvince();
                    String city = amapLocation.getCity();
                    String district = amapLocation.getDistrict();
                    String location = StringUtils.extractLocation(city, district);

                    LogUtils.e("citt=" + city + district + location);

                    //存取当前经纬度
                    SPUtils.setString(Constant.CURRENTLAT, Double.toString(currentLat));
                    SPUtils.setString(Constant.CURRENTLON, Double.toString(currentLon));

                    LogUtils.i("currentLat : " + currentLat + " currentLon : " + currentLon + "gaode:" + city);
                    amapLocation.getAccuracy();//获取精度信息
                    lng = Double.toString(currentLon);
                    lat = Double.toString(currentLat);

                    mPresenter.getNearbyShop(lng, lat);

                    //推荐
                    mPresenter.getIndexRecom(setIndexRecomMap());
                    //热销
                    mPresenter.getIndexSell(setIndexMap());

                    mPresenter.getTabTitle();
                    tvCityName.setText(city);
                } else {
                    //                            //定位失败

                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    LogUtils.e("location Error, ErrCode:" + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
//        }
    };




}
